﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;

namespace ChicagoDealsN
{
    public class DataPurchaseHistory
    {
        private string strConnect = "Data Source=localhost\\sqlexpress;Initial Catalog=yvyas;Integrated Security=True";

        private string getConnection() { return strConnect; }

        public void newPurchaseHistory(int User_Id, int Deals_Id, DateTime Pur_Date)
        { 
            SqlConnection conPubs;
            SqlCommand cmdCreate, cmdUpdateQty, cmdUpdateBalance;
            string Conn = getConnection();
            conPubs = new SqlConnection(Conn);
            
            try
            {
                    conPubs.Open();
                    // Create new entry in Purchase_History
                    cmdCreate = new SqlCommand("INSERT INTO Purchase_History (User_Id, Deal_Id, Redeemed, Purchased_Date, Redeemed_Date, Redeem_Code) VALUES (@User_Id, @Deal_Id, @Redeemed, @Purchase_Date,@Redeem_Date, @Redeem_Code)", conPubs);

                    cmdCreate.Parameters.AddWithValue("@User_Id", User_Id);
                    cmdCreate.Parameters.AddWithValue("@Deal_Id", Deals_Id);
                    cmdCreate.Parameters.AddWithValue("@Redeemed", 0);
                    cmdCreate.Parameters.AddWithValue("@Purchase_Date", Pur_Date);
                    cmdCreate.Parameters.AddWithValue("@Redeem_Date", Pur_Date);
                    cmdCreate.Parameters.AddWithValue("@Redeem_Code", getRedeemCode(10,true));
                    
                    
                    
                    // Update Qty in Deals
                    cmdUpdateQty = new SqlCommand("UPDATE Deals SET Quantity=Quantity-1 WHERE Deal_Id=@Deal_Id", conPubs);
                    cmdUpdateQty.Parameters.AddWithValue("@Deal_Id", Deals_Id);

                    cmdUpdateQty.ExecuteNonQuery();
                    cmdCreate.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                //return false;
                throw e;
            }
            finally
            {
                conPubs.Close();
            }

        }

        public bool updateBalance(int userId, int balToSet)
        {
            SqlConnection conPubs;
            SqlCommand cmdUpdateBalance;
            string Conn = getConnection();
            conPubs = new SqlConnection(Conn);
            try
            {
                conPubs.Open();
                //deduct money from user a/c
                cmdUpdateBalance = new SqlCommand("UPDATE Users SET Balance=@Points WHERE User_Id=@UserId", conPubs);
                cmdUpdateBalance.Parameters.AddWithValue("@Points", balToSet);
                cmdUpdateBalance.Parameters.AddWithValue("@UserId", userId);

                return (cmdUpdateBalance.ExecuteNonQuery() > 0) ? true : false;    
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conPubs.Close();
            }
            
        }

        public DataSet getPurchaseHistoryFromUserId(int User_Id)
        {
            SqlConnection conPubs;
            SqlCommand cmdGetAllPurchaseHistroy;
            string conn = getConnection();
            conPubs = new SqlConnection(conn);
            DataSet set = new DataSet();
            try
            {
                conPubs.Open();
                cmdGetAllPurchaseHistroy = new SqlCommand("select * from Purchase_History ph Left join Deals d on ph.Deal_Id=d.Deal_Id where ph.User_Id="+User_Id);
                SqlDataAdapter da = new SqlDataAdapter(cmdGetAllPurchaseHistroy.CommandText, conPubs);
                da.Fill(set, "AllPUrchaseDoneByUser");
            }
            catch (Exception e)
            {
                throw e;
            }
            finally 
            {
                conPubs.Close();
            }
            return set;
        }

        public bool DLRedeemCode(string code,DateTime red_date)
        {
            SqlConnection conPubs;
            SqlCommand cmdUpdate;
            string conn = getConnection();
            conPubs = new SqlConnection(conn);
            DataSet set = new DataSet();
            try
            {
                conPubs.Open();
                cmdUpdate = new SqlCommand("update Purchase_History set Redeemed=1,Redeemed_Date=@Red_Date where Redeem_Code=@Code and Redeemed=0", conPubs);
                cmdUpdate.Parameters.AddWithValue("@Code",code);
                cmdUpdate.Parameters.AddWithValue("@Red_Date", red_date);
                cmdUpdate.ExecuteNonQuery();

                if (cmdUpdate.ExecuteNonQuery() > 0)
                    return true;
                else
                    return false;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conPubs.Close();
            }
            return true;
        }

        /// <summary>
        /// Generates a random string with the given length
        /// </summary>
        /// <param name="size">Size of the string</param>
        /// <param name="lowerCase">If true, generate lowercase string</param>
        /// <returns>Random string</returns>
        private string getRedeemCode(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch ;
            for(int i=0; i<size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
                builder.Append(ch); 
            }
            if(lowerCase)
            return builder.ToString().ToLower();
            return builder.ToString();
        }
       
    }
}